from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QListWidget,
                             QLineEdit, QPushButton, QLabel, QListWidgetItem,
                             QFrame, QComboBox, QTextEdit, QScrollArea,
                             QSplitter, QMessageBox, QDialog, QFormLayout,
                             QSpinBox, QDialogButtonBox, QTabWidget,
                             QProgressBar, QMenu, QToolBar, QStatusBar,
                             QCheckBox)
from PyQt6.QtCore import pyqtSignal, Qt, QTimer, QThread, QObject
from PyQt6.QtGui import QAction, QIcon
from question_bank import QuestionBank, Question
import json
import os
from datetime import datetime
from typing import List
import markdown

class StreamWorker(QObject):
    """流式传输工作线程"""
    finished = pyqtSignal()
    error = pyqtSignal(str)
    text_received = pyqtSignal(str)
    
    def __init__(self, message):
        super().__init__()
        self.message = message
        self.is_running = True
        
    def run(self):
        try:
            # 这里添加实际的流式传输逻辑
            # 示例：模拟流式传输
            for char in self.message:
                if not self.is_running:
                    break
                self.text_received.emit(char)
                QThread.msleep(50)  # 模拟网络延迟
            self.finished.emit()
        except Exception as e:
            self.error.emit(str(e))
            
    def stop(self):
        self.is_running = False

class QuestionListItem(QWidget):
    def __init__(self, question):
        super().__init__()
        self.question = question
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 题目内容
        question_text = str(self.question.get('question', '')) if isinstance(self.question, dict) else str(self.question.question)
        question_label = QLabel(question_text)
        question_label.setWordWrap(True)
        question_label.setStyleSheet("font-size: 14px;")
        layout.addWidget(question_label)
        
        # 知识点标签
        tags_layout = QHBoxLayout()
        knowledge_tags = []
        
        # 获取知识点标签
        if isinstance(self.question, dict):
            tags = self.question.get('tags', {})
            if isinstance(tags, dict):
                knowledge_tags = tags.get('knowledge_tags', [])
        else:
            tags = self.question.tags
            if isinstance(tags, dict):
                knowledge_tags = tags.get('knowledge_tags', [])
        
        # 显示知识点标签
        for tag in knowledge_tags[:3]:
            tag_label = QLabel(str(tag))
            tag_label.setStyleSheet("""
                background-color: #3D3D3D;
                color: #FFFFFF;
                padding: 2px 6px;
                border-radius: 3px;
                margin-right: 4px;
                font-size: 14px;
            """)
            tags_layout.addWidget(tag_label)
        
        tags_layout.addStretch()
        layout.addLayout(tags_layout)
        
        # 复习状态
        review_status = "未复习"
        last_review = None
        if isinstance(self.question, dict):
            last_review = self.question.get('last_review_date')
        else:
            last_review = self.question.last_review_date
            
        if last_review:
            try:
                last_review_date = datetime.strptime(last_review, '%Y-%m-%d')
                days = (datetime.now() - last_review_date).days
                if days <= 1:
                    review_status = "今天复习"
                elif days <= 3:
                    review_status = "最近复习"
                else:
                    review_status = "已复习"
            except:
                pass
        
        # 掌握程度
        mastery = "待加强"
        mastery_level = 0.0
        if isinstance(self.question, dict):
            mastery_level = self.question.get('mastery_level', 0.0)
        else:
            mastery_level = self.question.mastery_level
            
        if mastery_level >= 0.8:
            mastery = "已掌握"
        elif mastery_level >= 0.6:
            mastery = "良好"
        elif mastery_level >= 0.4:
            mastery = "一般"
        
        # 状态标签
        status_layout = QHBoxLayout()
        
        # 复习状态标签
        review_label = QLabel(review_status)
        review_label.setStyleSheet(f"""
            padding: 2px 6px;
            border-radius: 3px;
            background-color: {
                "#4CAF50" if review_status == "今天复习" else
                "#2196F3" if review_status == "最近复习" else
                "#9E9E9E" if review_status == "已复习" else
                "#FF9800"
            };
            color: white;
            font-size: 14px;
        """)
        status_layout.addWidget(review_label)
        
        # 掌握程度标签
        mastery_label = QLabel(mastery)
        mastery_label.setStyleSheet(f"""
            padding: 2px 6px;
            border-radius: 3px;
            background-color: {
                "#4CAF50" if mastery == "已掌握" else
                "#2196F3" if mastery == "良好" else
                "#FF9800" if mastery == "一般" else
                "#F44336"
            };
            color: white;
            font-size: 14px;
        """)
        status_layout.addWidget(mastery_label)
        
        # 收藏状态
        is_favorite = False
        if isinstance(self.question, dict):
            is_favorite = self.question.get('is_favorite', False)
        else:
            is_favorite = self.question.is_favorite
            
        if is_favorite:
            favorite_label = QLabel("★")
            favorite_label.setStyleSheet("""
                color: #FFD700;
                font-size: 18px;
            """)
            status_layout.addWidget(favorite_label)
        
        status_layout.addStretch()
        layout.addLayout(status_layout)
        
        # 设置样式
        self.setStyleSheet("""
            QWidget {
                background-color: #2D2D2D;
                color: #FFFFFF;
                border-radius: 4px;
                padding: 8px;
                font-size: 14px;
            }
            
            QLabel {
                color: #FFFFFF;
                font-size: 14px;
            }
        """)

class EditQuestionDialog(QDialog):
    def __init__(self, question: Question, parent=None):
        super().__init__(parent)
        self.question = question
        self.setWindowTitle("编辑题目")
        self.setModal(True)
        self.init_ui()
    
    def init_ui(self):
        layout = QFormLayout()
        self.setLayout(layout)
        
        # 题目内容
        self.question_edit = QTextEdit()
        self.question_edit.setText(self.question.question)
        layout.addRow("题目内容:", self.question_edit)
        
        # 答案
        self.answer_edit = QTextEdit()
        self.answer_edit.setText(self.question.answer)
        layout.addRow("答案:", self.answer_edit)
        
        # 知识点标签
        self.knowledge_tags = QListWidget()
        self.knowledge_tags.setSelectionMode(QListWidget.SelectionMode.MultiSelection)
        self.knowledge_tags.addItems(self.question.tags.get('knowledge_tags', []))
        layout.addRow("知识点标签:", self.knowledge_tags)
        
        # 难度
        self.difficulty = QSpinBox()
        self.difficulty.setRange(1, 3)
        self.difficulty.setValue(self.question.tags.get('difficulty', 1))
        layout.addRow("难度:", self.difficulty)
        
        # 按钮
        buttons = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | 
            QDialogButtonBox.StandardButton.Cancel
        )
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addRow(buttons)
    
    def get_edited_question(self) -> Question:
        return Question(
            question=self.question_edit.toPlainText(),
            answer=self.answer_edit.toPlainText(),
            steps=self.question.steps,
            tags={
                "knowledge_tags": [item.text() for item in self.knowledge_tags.selectedItems()],
                "difficulty": self.difficulty.value()
            },
            is_favorite=self.question.is_favorite,
            last_review=self.question.last_review,
            review_count=self.question.review_count,
            correct_count=self.question.correct_count
        )

class QuestionDetailWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.question_bank = None
        self.current_question = None
        self.current_question_index = -1
        self.current_questions = []
        self.right_panel = None
        self.thread = None
        self.threads = []
        self.stream_worker = None
        self.conversation_history = []  # 添加对话历史记录
        self.init_ui()
        self.setup_styles()
    
    def setup_styles(self):
        """设置样式"""
        self.setStyleSheet("""
            QWidget {
                background-color: #1E1E1E;
                color: #FFFFFF;
                font-size: 14px;
            }
            QLabel {
                color: #FFFFFF;
                font-size: 14px;
            }
            QTextEdit {
                background-color: #2D2D2D;
                border: 1px solid #404040;
                border-radius: 4px;
                padding: 8px;
                color: #FFFFFF;
                font-size: 14px;
            }
            QProgressBar {
                border: 1px solid #404040;
                border-radius: 4px;
                text-align: center;
                background-color: #2D2D2D;
                font-size: 14px;
            }
            QProgressBar::chunk {
                background-color: #2196F3;
                border-radius: 3px;
            }
        """)
    
    def init_ui(self):
        # 主布局
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(16, 16, 16, 16)
        main_layout.setSpacing(16)
        self.setLayout(main_layout)
        
        # 工具栏
        toolbar = QHBoxLayout()
        
        # 上一题按钮
        self.prev_button = QPushButton("上一题")
        self.prev_button.clicked.connect(self.show_previous_question)
        toolbar.addWidget(self.prev_button)
        
        # 下一题按钮
        self.next_button = QPushButton("下一题")
        self.next_button.clicked.connect(self.show_next_question)
        toolbar.addWidget(self.next_button)
        
        # 收藏按钮
        self.favorite_button = QPushButton("收藏")
        self.favorite_button.setCheckable(True)
        self.favorite_button.clicked.connect(self.toggle_favorite)
        toolbar.addWidget(self.favorite_button)
        
        # 评分按钮
        self.rate_button = QPushButton("评分")
        self.rate_button.clicked.connect(self.rate_question)
        toolbar.addWidget(self.rate_button)
        
        # 导出按钮
        self.export_button = QPushButton("导出")
        self.export_button.clicked.connect(self.export_question)
        toolbar.addWidget(self.export_button)
        
        # 分享按钮
        self.share_button = QPushButton("分享")
        self.share_button.clicked.connect(self.share_question)
        toolbar.addWidget(self.share_button)
        
        toolbar.addStretch()
        main_layout.addLayout(toolbar)
        
        # 标签区域
        self.tags_layout = QHBoxLayout()
        self.tags_layout.setSpacing(8)
        main_layout.addLayout(self.tags_layout)
        
        # 分割器
        splitter = QSplitter(Qt.Orientation.Vertical)
        
        # 题目区域（较大）
        question_group = QFrame()
        question_layout = QVBoxLayout()
        question_group.setLayout(question_layout)
        question_layout.addWidget(QLabel("题目内容："))
        self.question_text = QTextEdit()
        self.question_text.setReadOnly(True)
        question_layout.addWidget(self.question_text)
        splitter.addWidget(question_group)
        
        # 答案区域（较小）
        answer_group = QFrame()
        answer_layout = QVBoxLayout()
        answer_group.setLayout(answer_layout)
        answer_layout.addWidget(QLabel("答案："))
        self.answer_text = QTextEdit()
        self.answer_text.setReadOnly(True)
        self.answer_text.setMaximumHeight(100)  # 限制答案区域高度
        answer_layout.addWidget(self.answer_text)
        splitter.addWidget(answer_group)
        
        # 解析区域（较大）
        steps_group = QFrame()
        steps_layout = QVBoxLayout()
        steps_group.setLayout(steps_layout)
        steps_layout.addWidget(QLabel("解题步骤："))
        self.steps_area = QScrollArea()
        self.steps_area.setWidgetResizable(True)
        self.steps_widget = QWidget()
        self.steps_layout = QVBoxLayout()
        self.steps_widget.setLayout(self.steps_layout)
        self.steps_area.setWidget(self.steps_widget)
        steps_layout.addWidget(self.steps_area)
        splitter.addWidget(steps_group)
        
        # 设置分割器的初始大小
        splitter.setSizes([200, 100, 400])  # 题目:答案:步骤 = 2:1:4
        
        # 学习进度区域
        progress_layout = QHBoxLayout()
        self.progress_bar = QProgressBar()
        self.progress_bar.setRange(0, 100)
        progress_layout.addWidget(QLabel("掌握程度："))
        progress_layout.addWidget(self.progress_bar)
        main_layout.addLayout(progress_layout)
        
        main_layout.addWidget(splitter)
        
        # 状态栏
        self.status_bar = QStatusBar()
        main_layout.addWidget(self.status_bar)
    
    def set_right_panel(self, right_panel):
        """设置右侧面板引用"""
        self.right_panel = right_panel
    
    def cleanup_threads(self):
        """清理已完成的线程"""
        # 停止所有正在运行的流式传输
        if self.stream_worker and self.stream_worker.is_running:
            self.stream_worker.stop()
            
        # 清理已完成的线程
        self.threads = [t for t in self.threads if t.isRunning()]
        
    def add_thread(self, thread):
        """添加新线程并清理旧线程"""
        self.cleanup_threads()
        self.threads.append(thread)
        self.thread = thread  # 保存当前线程引用
        
    def start_stream(self, message):
        """启动流式传输"""
        # 清理之前的流式传输
        self.cleanup_threads()
        
        # 创建新的流式传输工作线程
        self.stream_worker = StreamWorker(message)
        self.stream_worker.text_received.connect(self.on_text_received)
        self.stream_worker.finished.connect(self.on_stream_finished)
        self.stream_worker.error.connect(self.on_stream_error)
        
        # 创建并启动线程
        thread = QThread()
        self.stream_worker.moveToThread(thread)
        thread.started.connect(self.stream_worker.run)
        self.add_thread(thread)
        thread.start()
        
    def on_text_received(self, text):
        """处理接收到的文本"""
        if self.right_panel:
            self.right_panel.append_text(text)
            # 将AI的回复添加到对话历史
            self.conversation_history.append({"role": "assistant", "content": text})
            
    def on_stream_finished(self):
        """流式传输完成"""
        print("流式传输完成")
        # 通知右侧面板对话完成
        if self.right_panel:
            self.right_panel.on_conversation_complete(self.conversation_history)
        
    def on_stream_error(self, error):
        """流式传输错误"""
        print(f"流式传输错误: {error}")
        QMessageBox.critical(self, "错误", f"流式传输错误: {error}")
        
    def __del__(self):
        """析构函数，确保所有线程都被正确清理"""
        try:
            # 停止流式传输
            if self.stream_worker:
                self.stream_worker.stop()
                
            # 等待所有线程完成
            for thread in self.threads:
                if thread.isRunning():
                    thread.wait()
        except:
            pass
    
    def load_question(self, question, index: int = -1):
        """加载题目内容"""
        try:
            # 如果question是字典，转换为Question对象
            if isinstance(question, dict):
                question = Question(
                    id=question.get('id', str(index)),
                    question=question.get('question', ''),
                    answer=question.get('answer', ''),
                    steps=question.get('steps', []),
                    tags=question.get('tags', {}),
                    is_favorite=question.get('is_favorite', False),
                    last_review_date=question.get('last_review_date'),
                    review_count=question.get('review_count', 0),
                    correct_count=question.get('correct_count', 0)
                )
            
            self.current_question = question
            self.current_question_index = index
            
            # 更新题目内容，确保是字符串类型
            question_text = str(question.question) if question.question else ''
            answer_text = str(question.answer) if question.answer else ''
            
            self.question_text.setPlainText(question_text)
            self.answer_text.setPlainText(answer_text)
            
            # 更新标签
            self.update_tags(question.tags)
            
            # 更新收藏状态
            self.favorite_button.setChecked(question.is_favorite)
            
            # 更新导航按钮状态
            self.update_navigation_buttons()
            
            # 清空步骤
            self.clear_steps()
            
            # 如果有步骤，显示步骤
            if question.steps:
                self.show_steps(question.steps)
            
            # 更新掌握程度
            mastery_level = question.mastery_level if hasattr(question, 'mastery_level') else 0.0
            self.progress_bar.setValue(int(mastery_level * 100))
            
            # 更新状态栏
            if self.question_bank and self.question_bank.questions:
                self.status_bar.showMessage(f"题目 {index + 1}/{len(self.question_bank.questions)}")
            
            # 通知右侧面板加载题目
            if self.right_panel:
                # 确保之前的线程已经完成
                self.cleanup_threads()
                # 清空对话历史
                self.conversation_history = []
                # 添加初始提示
                initial_prompt = f"这是一道题目：\n{question_text}\n\n答案：{answer_text}\n\n请帮助我理解这道题。"
                self.conversation_history.append({"role": "system", "content": initial_prompt})
                self.right_panel.load_question(question, index, self.conversation_history)
                
        except Exception as e:
            print(f"加载题目时出错: {e}")
            QMessageBox.critical(self, "错误", f"加载题目时出错: {str(e)}")
    
    def show_steps(self, steps):
        """显示解题步骤"""
        try:
            self._clear_step_widgets()
            
            if not steps:
                return
            
            for step in steps:
                if not isinstance(step, dict):
                    continue
                    
                step_id = step.get('id', '')
                step_text = step.get('step', '')
                title = f"步骤 {step_id}：{step_text}"
                
                tags = step.get('tags', {})
                if not isinstance(tags, dict):
                    tags = {}
                    
                details = []
                if 'known' in tags:
                    details.append(f"已知条件：{tags['known']}")
                if 'goal' in tags:
                    details.append(f"目标：{tags['goal']}")
                if 'thinking' in tags:
                    details.append(f"思考过程：{tags['thinking']}")
                if 'reason' in tags:
                    details.append(f"原因：{tags['reason']}")
                if 'error_analysis' in tags:
                    details.append(f"错误分析：{tags['error_analysis']}")
                
                # 创建步骤容器
                step_container = QFrame()
                step_container.setStyleSheet("""
                    QFrame {
                        background-color: #2D2D2D;
                        border-radius: 4px;
                        margin: 4px 0;
                    }
                """)
                step_layout = QVBoxLayout()
                step_container.setLayout(step_layout)
                
                # 添加标题
                title_label = QLabel(title)
                title_label.setStyleSheet("""
                    QLabel {
                        color: #2196F3;
                        font-weight: bold;
                        margin-bottom: 4px;
                    }
                """)
                step_layout.addWidget(title_label)
                
                # 添加详情
                for detail in details:
                    detail_label = QLabel(detail)
                    detail_label.setWordWrap(True)
                    detail_label.setStyleSheet("""
                        QLabel {
                            color: #FFFFFF;
                            margin: 2px 0;
                        }
                    """)
                    step_layout.addWidget(detail_label)
                
                self.steps_layout.addWidget(step_container)
            
            # 添加弹性空间
            self.steps_layout.addStretch()
            
        except Exception as e:
            print(f"显示解题步骤时出错: {e}")
    
    def _clear_step_widgets(self):
        """清除所有步骤组件"""
        while self.steps_layout.count():
            item = self.steps_layout.takeAt(0)
            if item.widget():
                item.widget().deleteLater()
    
    def show_next_question(self):
        """显示下一题"""
        try:
            if not self.current_questions:
                return
                
            if self.current_question_index < len(self.current_questions) - 1:
                self.current_question_index += 1
                question = self.current_questions[self.current_question_index]
                self.load_question(question, self.current_question_index)
        except Exception as e:
            print(f"显示下一题时出错: {e}")
            QMessageBox.critical(self, "错误", f"显示下一题时出错: {str(e)}")
    
    def show_previous_question(self):
        """显示上一题"""
        try:
            if not self.current_questions:
                return
                
            if self.current_question_index > 0:
                self.current_question_index -= 1
                question = self.current_questions[self.current_question_index]
                self.load_question(question, self.current_question_index)
        except Exception as e:
            print(f"显示上一题时出错: {e}")
            QMessageBox.critical(self, "错误", f"显示上一题时出错: {str(e)}")
    
    def rate_question(self):
        """评分"""
        if not self.current_question:
            QMessageBox.warning(self, "警告", "请先选择一道题目")
            return
        
        # 第一步：确认是否答对
        reply = QMessageBox.question(
            self,
            "评分",
            "这道题你做对了吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        is_correct = reply == QMessageBox.StandardButton.Yes
        
        wrong_steps = []
        if not is_correct and self.current_question.steps:
            # 如果答错了，询问具体哪些步骤出错
            steps = self.current_question.steps
            if steps:
                step_dialog = QDialog(self)
                step_dialog.setWindowTitle("选择错误的步骤")
                layout = QVBoxLayout()
                
                # 添加说明标签
                layout.addWidget(QLabel("请选择你做错的步骤："))
                
                # 创建复选框列表
                checkboxes = []
                for i, step in enumerate(steps):
                    step_content = step.get('content', '') if isinstance(step, dict) else str(step)
                    checkbox = QCheckBox(f"步骤 {i+1}: {step_content}")
                    checkboxes.append(checkbox)
                    layout.addWidget(checkbox)
                
                # 添加确定按钮
                button_box = QDialogButtonBox(
                    QDialogButtonBox.StandardButton.Ok | 
                    QDialogButtonBox.StandardButton.Cancel
                )
                button_box.accepted.connect(step_dialog.accept)
                button_box.rejected.connect(step_dialog.reject)
                layout.addWidget(button_box)
                
                step_dialog.setLayout(layout)
                
                if step_dialog.exec() == QDialog.DialogCode.Accepted:
                    # 收集选中的错误步骤
                    wrong_steps = [i for i, cb in enumerate(checkboxes) if cb.isChecked()]
        
        if self.current_question_index >= 0:
            self.question_bank.update_review(
                self.current_question_index, 
                is_correct,
                wrong_steps if not is_correct else None
            )
            self.current_question = self.question_bank.questions[self.current_question_index]
            self.load_question(self.current_question, self.current_question_index)
            
            # 显示反馈
            if is_correct:
                status = "答对了！"
            else:
                if wrong_steps:
                    status = f"答错了，需要加强步骤 {', '.join(str(i+1) for i in wrong_steps)} 的练习"
                else:
                    status = "答错了，继续加油！"
            self.status_bar.showMessage(status, 3000)  # 显示3秒
    
    def export_question(self):
        """导出题目"""
        if not self.current_question:
            QMessageBox.warning(self, "警告", "请先选择一道题目")
            return
        
        try:
            # 创建导出目录
            export_dir = "exports"
            if not os.path.exists(export_dir):
                os.makedirs(export_dir)
            
            # 生成文件名
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"{export_dir}/question_{timestamp}.json"
            
            # 导出题目
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(asdict(self.current_question), f, ensure_ascii=False, indent=2)
            
            QMessageBox.information(self, "成功", f"题目已导出到：{filename}")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"导出失败：{str(e)}")
    
    def share_question(self):
        """分享题目"""
        if not self.current_question:
            QMessageBox.warning(self, "警告", "请先选择一道题目")
            return
        
        # TODO: 实现分享功能
        QMessageBox.information(self, "提示", "分享功能开发中...")

    def update_navigation_buttons(self):
        """更新导航按钮状态"""
        if not self.current_questions:
            self.prev_button.setEnabled(False)
            self.next_button.setEnabled(False)
            return
            
        self.prev_button.setEnabled(self.current_question_index > 0)
        self.next_button.setEnabled(self.current_question_index < len(self.current_questions) - 1)

    def update_tags(self, tags: dict):
        """更新标签显示
        
        Args:
            tags (dict): 标签字典
        """
        # 清除现有标签
        while self.tags_layout.count():
            item = self.tags_layout.takeAt(0)
            if item.widget():
                item.widget().deleteLater()
        
        if not tags:
            return
            
        # 显示知识点标签
        if 'knowledge_tags' in tags and tags['knowledge_tags']:
            for tag in tags['knowledge_tags']:
                tag_label = QLabel(str(tag))
                tag_label.setStyleSheet("""
                    background-color: #3D3D3D;
                    color: #FFFFFF;
                    padding: 4px 8px;
                    border-radius: 4px;
                """)
                self.tags_layout.addWidget(tag_label)
        
        # 显示难度标签
        if 'difficulty' in tags:
            difficulty = tags['difficulty']
            difficulty_text = {
                1: "简单",
                2: "中等",
                3: "困难"
            }.get(difficulty, "未知")
            
            difficulty_label = QLabel(difficulty_text)
            difficulty_label.setStyleSheet(f"""
                background-color: {
                    "#4CAF50" if difficulty == 1 else
                    "#FFC107" if difficulty == 2 else
                    "#F44336"
                };
                color: #FFFFFF;
                padding: 4px 8px;
                border-radius: 4px;
            """)
            self.tags_layout.addWidget(difficulty_label)
        
        self.tags_layout.addStretch()
    
    def toggle_favorite(self):
        """切换收藏状态"""
        if not self.current_question:
            return
            
        self.current_question.is_favorite = not self.current_question.is_favorite
        self.favorite_button.setChecked(self.current_question.is_favorite)
        
        # 更新题库中的题目
        if self.question_bank and self.current_question_index >= 0:
            self.question_bank.questions[self.current_question_index] = self.current_question
            
        # 显示状态
        status = "已收藏" if self.current_question.is_favorite else "已取消收藏"
        self.status_bar.showMessage(status, 2000)  # 显示2秒

    def clear_steps(self):
        """清空步骤显示"""
        self._clear_step_widgets()

class QuestionListWidget(QWidget):
    question_selected = pyqtSignal(Question, int)  # 题目选择信号
    question_deleted = pyqtSignal(int)  # 添加删除信号
    
    def __init__(self):
        super().__init__()
        self.question_bank = QuestionBank()  # 初始化题库
        self.current_questions = []
        self.current_page = 1
        self.page_size = 30
        self.init_ui()
        self.setup_styles()
        self.setup_shortcuts()
        
        # 加载所有题目
        self.load_content()
    
    def init_ui(self):
        """初始化用户界面"""
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 搜索框
        search_layout = QHBoxLayout()
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入标签关键词搜索相关题目...")
        self.search_input.returnPressed.connect(self.on_search)
        search_layout.addWidget(self.search_input)
        
        search_button = QPushButton("搜索")
        search_button.clicked.connect(self.on_search)
        search_layout.addWidget(search_button)
        
        # 添加清除搜索按钮
        clear_button = QPushButton("清除")
        clear_button.clicked.connect(self.clear_search)
        search_layout.addWidget(clear_button)
        
        layout.addLayout(search_layout)
        
        # 题目列表
        self.question_list = QListWidget()
        self.question_list.setSpacing(5)  # 设置项目间距
        self.question_list.itemClicked.connect(self.on_question_selected)
        self.question_list.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)  # 启用右键菜单
        self.question_list.customContextMenuRequested.connect(self.show_context_menu)  # 连接右键菜单信号
        layout.addWidget(self.question_list)
        
        # 分页控件
        page_layout = QHBoxLayout()
        
        # 上一页按钮
        self.prev_button = QPushButton("上一页")
        self.prev_button.clicked.connect(self.prev_page)
        page_layout.addWidget(self.prev_button)
        
        # 页码显示
        self.page_label = QLabel()
        page_layout.addWidget(self.page_label)
        
        # 下一页按钮
        self.next_button = QPushButton("下一页")
        self.next_button.clicked.connect(self.next_page)
        page_layout.addWidget(self.next_button)
        
        layout.addLayout(page_layout)
            
        # 状态栏
        self.status_bar = QStatusBar()
        self.status_bar.showMessage("就绪")
        layout.addWidget(self.status_bar)
    
    def setup_styles(self):
        """设置样式"""
        self.setStyleSheet("""
            QWidget {
                background-color: #1E1E1E;
                color: #FFFFFF;
                font-size: 14px;
            }
            
            QLineEdit {
                background-color: #2D2D2D;
                border: 1px solid #404040;
                border-radius: 4px;
                padding: 8px;
                color: #FFFFFF;
                font-size: 14px;
            }
            
            QPushButton {
                background-color: #2196F3;
                color: #FFFFFF;
                border: none;
                border-radius: 4px;
                padding: 8px 16px;
                font-size: 14px;
            }
            
            QPushButton:hover {
                background-color: #1976D2;
            }
            
            QPushButton:pressed {
                background-color: #1565C0;
            }
            
            QListWidget {
                background-color: #2D2D2D;
                border: 1px solid #404040;
                border-radius: 4px;
                font-size: 14px;
            }
            
            QListWidget::item {
                padding: 8px;
            }
            
            QListWidget::item:selected {
                background-color: #3D3D3D;
            }

            QLabel {
                font-size: 14px;
            }

            QTextEdit {
                font-size: 14px;
            }
        """)
    
    def setup_shortcuts(self):
        """设置快捷键"""
        # 搜索
        search_action = QAction("搜索", self)
        search_action.setShortcut("Ctrl+F")
        search_action.triggered.connect(lambda: self.search_input.setFocus())
        self.addAction(search_action)
        
        # 清除搜索
        clear_action = QAction("清除搜索", self)
        clear_action.setShortcut("Ctrl+E")
        clear_action.triggered.connect(self.clear_search)
        self.addAction(clear_action)
    
    def update_questions(self, questions: List[Question]):
        """更新题目列表
        
        Args:
            questions (List[Question]): 要显示的题目列表
        """
        self.current_questions = questions
        self.current_page = 1  # 重置到第一页
        self.update_question_list()
        self.update_page_info()
        self.status_bar.showMessage(f"显示 {len(questions)} 道题目")
    
    def update_question_list(self):
        """更新题目列表显示"""
        self.question_list.clear()
        
        # 计算当前页的题目范围
        start_idx = (self.current_page - 1) * self.page_size
        end_idx = min(start_idx + self.page_size, len(self.current_questions))
        
        # 显示当前页的题目
        for question in self.current_questions[start_idx:end_idx]:
            item = QListWidgetItem()
            item.setSizeHint(QuestionListItem(question).sizeHint())
            self.question_list.addItem(item)
            self.question_list.setItemWidget(item, QuestionListItem(question))
    
    def update_page_info(self):
        """更新分页信息"""
        total_pages = (len(self.current_questions) + self.page_size - 1) // self.page_size
        self.page_label.setText(f"第 {self.current_page} 页 / 共 {total_pages} 页")
        
        # 更新按钮状态
        self.prev_button.setEnabled(self.current_page > 1)
        self.next_button.setEnabled(self.current_page < total_pages)
    
    def prev_page(self):
        """显示上一页"""
        if self.current_page > 1:
            self.current_page -= 1
            self.update_question_list()
            self.update_page_info()
    
    def next_page(self):
        """显示下一页"""
        total_pages = (len(self.current_questions) + self.page_size - 1) // self.page_size
        if self.current_page < total_pages:
            self.current_page += 1
            self.update_question_list()
            self.update_page_info()
    
    def load_content(self, knowledge_tag: str = None):
        """加载题目列表
        
        Args:
            knowledge_tag (str, optional): 知识点标签. Defaults to None.
        """
        if knowledge_tag:
            # 按知识点筛选
            questions = self.question_bank.get_questions_by_knowledge(knowledge_tag)
        else:
            # 显示所有题目
            questions = self.question_bank.get_all_questions()
            
        # 过滤掉格式不正确的题目
        filtered_questions = []
        for q in questions:
            if isinstance(q, dict):
                # 检查是否只包含id、subject和content字段
                if set(q.keys()) == {'id', 'subject', 'content'}:
                    print(f"跳过格式不正确的题目: {q['id']}")
                    continue
            filtered_questions.append(q)
            
        self.current_questions = filtered_questions
        self.status_bar.showMessage(f"显示 {len(filtered_questions)} 道题目")
        
        # 重置到第一页并更新显示
        self.current_page = 1
        self.update_question_list()
        self.update_page_info()
    
    def on_question_selected(self, item):
        """处理题目选择"""
        try:
            if not item:
                return
                
            index = self.question_list.row(item)
            if 0 <= index < len(self.current_questions):
                # 计算实际题目索引
                actual_index = (self.current_page - 1) * self.page_size + index
                if 0 <= actual_index < len(self.current_questions):
                    question = self.current_questions[actual_index]
                    if question:
                        # 如果 question 是字典，转换为 Question 对象
                        if isinstance(question, dict):
                            question = Question(
                                id=question.get('id', str(actual_index)),  # 添加 id 参数
                                question=question.get('question', ''),
                                answer=question.get('answer', ''),
                                steps=question.get('steps', []),
                                tags=question.get('tags', {}),
                                is_favorite=question.get('is_favorite', False),
                                last_review_date=question.get('last_review_date'),
                                review_count=question.get('review_count', 0),
                                correct_count=question.get('correct_count', 0)
                            )
                        self.question_selected.emit(question, actual_index)
        except Exception as e:
            print(f"选择题目时出错: {e}")
            QMessageBox.warning(self, "错误", f"选择题目时出错: {str(e)}")
    
    def on_search(self):
        """处理搜索"""
        keyword = self.search_input.text().strip()
        if keyword:
            # 搜索所有题目中的标签
            matched_questions = []
            for q in self.question_bank.questions:
                # 获取题目的所有标签
                tags = []
                if isinstance(q, dict):
                    if 'tags' in q and isinstance(q['tags'], dict):
                        # 获取知识点标签
                        if 'knowledge_tags' in q['tags']:
                            tags.extend(q['tags']['knowledge_tags'])
                        # 获取其他标签
                        for key, value in q['tags'].items():
                            if key != 'knowledge_tags' and isinstance(value, (str, int, float)):
                                tags.append(str(value))
                else:
                    if hasattr(q, 'tags') and isinstance(q.tags, dict):
                        # 获取知识点标签
                        if 'knowledge_tags' in q.tags:
                            tags.extend(q.tags['knowledge_tags'])
                        # 获取其他标签
                        for key, value in q.tags.items():
                            if key != 'knowledge_tags' and isinstance(value, (str, int, float)):
                                tags.append(str(value))
                
                # 检查是否有标签包含搜索关键词
                if any(keyword.lower() in str(tag).lower() for tag in tags):
                    matched_questions.append(q)
            
            self.current_questions = matched_questions
            self.current_page = 1  # 重置到第一页
            self.update_question_list()
            self.update_page_info()
            self.status_bar.showMessage(f"找到 {len(matched_questions)} 道包含标签 '{keyword}' 的题目")
            
            # 如果有搜索结果，自动选中第一项
            if self.current_questions:
                self.question_list.setCurrentRow(0)
                self.on_question_selected(self.question_list.currentItem())
    
    def clear_search(self):
        """清除搜索"""
        self.search_input.clear()
        self.load_content()
        
        # 清除选中状态
        self.question_list.clearSelection()
        self.status_bar.showMessage("已清除搜索")

    def show_context_menu(self, pos):
        """显示右键菜单"""
        menu = QMenu(self)
        
        # 删除操作
        delete_action = QAction("删除题目", self)
        delete_action.triggered.connect(self.delete_selected_question)
        menu.addAction(delete_action)
        
        # 编辑操作
        edit_action = QAction("编辑题目", self)
        edit_action.triggered.connect(self.edit_selected_question)
        menu.addAction(edit_action)
        
        menu.exec(self.question_list.mapToGlobal(pos))
    
    def delete_selected_question(self):
        """删除选中的题目"""
        current_item = self.question_list.currentItem()
        if not current_item:
            return
            
        # 获取题目索引
        index = self.question_list.row(current_item)
        if index < 0 or index >= len(self.current_questions):
            return
            
        # 确认删除
        reply = QMessageBox.question(
            self,
            "确认删除",
            "确定要删除这道题目吗？此操作不可恢复。",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            try:
                # 从题库中删除
                self.question_bank.delete_question(index)
                
                # 从当前列表中删除
                self.current_questions.pop(index)
                
                # 更新显示
                self.update_question_list()
                self.update_page_info()
                
                # 发送删除信号
                self.question_deleted.emit(index)
                
                self.status_bar.showMessage("题目已删除")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除题目失败: {str(e)}")
    
    def edit_selected_question(self):
        """编辑选中的题目"""
        current_item = self.question_list.currentItem()
        if not current_item:
            return
            
        # 获取题目索引
        index = self.question_list.row(current_item)
        if index < 0 or index >= len(self.current_questions):
            return
            
        # 获取题目对象
        question = self.current_questions[index]
        
        # 显示编辑对话框
        dialog = EditQuestionDialog(question, self)
        if dialog.exec() == QDialog.DialogCode.Accepted:
            try:
                # 获取编辑后的题目
                edited_question = dialog.get_edited_question()
                
                # 更新题库
                self.question_bank.edit_question(index, edited_question)
                
                # 更新当前列表
                self.current_questions[index] = edited_question
                
                # 更新显示
                self.update_question_list()
                
                self.status_bar.showMessage("题目已更新")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"更新题目失败: {str(e)}")

class CenterPanel(QWidget):
    question_selected = pyqtSignal(Question)  # 题目选择信号
    question_deleted = pyqtSignal(int)  # 添加删除信号
    
    def __init__(self, question_bank=None):
        super().__init__()
        self.question_bank = question_bank or QuestionBank()
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 创建选项卡
        self.tab_widget = QTabWidget()
        layout.addWidget(self.tab_widget)
        
        # 题目列表选项卡
        self.question_list = QuestionListWidget()
        self.question_list.question_selected.connect(self.on_question_selected)
        self.question_list.question_deleted.connect(self.on_question_deleted)  # 连接删除信号
        self.tab_widget.addTab(self.question_list, "题目列表")
        
        # 题目详情选项卡
        self.question_detail = QuestionDetailWidget()
        self.question_detail.question_bank = self.question_bank
        self.tab_widget.addTab(self.question_detail, "题目详情")
        
        # 连接筛选信号
        if hasattr(self.parent(), 'left_panel'):
            self.parent().left_panel.filter_changed.connect(self.on_filter_changed)
        
        # 加载所有题目
        self.load_content()
    
    def set_right_panel(self, right_panel):
        """设置右侧面板"""
        self.question_detail.set_right_panel(right_panel)
    
    def load_content(self, knowledge_tag: str = None):
        """加载题目内容
        
        Args:
            knowledge_tag (str, optional): 知识点标签. Defaults to None.
        """
        self.question_list.load_content(knowledge_tag)
    
    def filter_by_difficulty(self, difficulty: str):
        """按难度筛选题目
        
        Args:
            difficulty (str): 难度级别（"全部"、"简单"、"中等"、"困难"）
        """
        filters = {
            'difficulty': difficulty,
            'year': '全部',
            'review_status': '全部'
        }
        self.on_filter_changed(filters)
    
    def on_filter_changed(self, filters: dict):
        """处理筛选条件变化
        
        Args:
            filters (dict): 筛选条件字典
        """
        filtered_questions = self.question_bank.filter_questions(filters)
        self.question_list.update_questions(filtered_questions)
        # 更新题目详情面板的当前题目列表
        self.question_detail.current_questions = filtered_questions
    
    def on_question_selected(self, question: Question, index: int):
        """处理题目选择
        
        Args:
            question (Question): 选中的题目
            index (int): 题目索引
        """
        self.question_selected.emit(question)
        # 更新题目详情面板的当前题目列表
        self.question_detail.current_questions = self.question_list.current_questions
        self.question_detail.load_question(question, index)
        self.tab_widget.setCurrentIndex(1)  # 切换到题目详情选项卡 

    def on_question_deleted(self, index: int):
        """处理题目删除事件"""
        # 转发删除信号
        self.question_deleted.emit(index)
        
        # 更新题目详情面板
        if self.question_detail.current_question_index == index:
            self.question_detail.clear_steps()
            self.question_detail.current_question = None
            self.question_detail.current_question_index = -1 